package org.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.example.dto.InventoryRequest;
import org.example.dto.InventoryResponse;
import org.example.bean.Inventory;
import org.example.dao.InventoryDao;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class InventoryService {  //库存服务
  private final InventoryDao inventoryDao;
   @SneakyThrows
   public List<InventoryResponse> isInStock(List<String> skuCode) {                 //判断是否有库存
      log.info("Checking Inventory");
      QueryWrapper<Inventory> qw = Wrappers.<Inventory>query().in("sku", skuCode);
      return inventoryDao.selectList(qw)
              .stream()
              .map(inventory ->
                      InventoryResponse.builder()
                              .sku(inventory.getSku())
                              .isInStock(inventory.getQuantity() > 0 ? 1 : 0)
                              .quantity(inventory.getQuantity())
                              .build()
              ).collect(Collectors.toList());     ///collect方法完成流在转回列表
   }

   public void create(InventoryRequest request) {
      Inventory inventory = Inventory.builder()
              .sku(request.getSku())
              .quantity(request.getQuantity())
              .isInStock(request.getQuantity() > 0 ? 1 : 0)
              .build();
      inventoryDao.insert(inventory);
      log.info("inventory inserted!");
   }


   public void update(InventoryRequest request){          //更新方法
       Inventory inventory = Inventory.builder()
               .sku(request.getSku())
               .quantity(request.getQuantity())
               .build();
       inventoryDao.update(inventory);

   }
}
